package com.ssl.rms.interceptor;

import com.ssl.rms.constants.SystemConstant;
import com.ssl.rms.utils.JsonMapper;
import com.ssl.rms.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * 描述：token验证拦截器
 *
 * @author shi_senlin
 * @create 2018/04/29 15:35
 */
public class TokenInterceptor extends HandlerInterceptorAdapter {
    private static final Logger logger = LoggerFactory.getLogger(TokenInterceptor.class);

    /**
     * 请求预处理
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws
            Exception {
        String ip = StringUtils.getRemoteAddr(request);
        String url = request.getRequestURL().toString();
        String method = request.getMethod();
        Map<String, String[]> params = request.getParameterMap();
        logger.info("[{}],[{}],[{}],[{}]", ip, url, method, JsonMapper.toJsonString(params));
        request.setAttribute("url_start", System.currentTimeMillis());
        String token = request.getHeader(SystemConstant.HEADER_FOR_TOKEN);
        if (StringUtils.isBlank(token)) {
            logger.warn("token is not fount!token[{}]", token);
            /** 返回json */
            //responseOutWithJson(response, "没有找到token");
            //return false;
        }
        return super.preHandle(request, response, handler);
    }

    /**
     * preHandle方法返回值为true的时候才会执行,<br/>
     * postHandle是进行处理器拦截用的，它的执行时间是在Controller的方法调用之后执行，<br/>
     * 但是它会在DispatcherServlet进行视图的渲染之前执行，也就是说在这个方法中你可以对ModelAndView进行操作
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView
            modelAndView) throws Exception {
        long finished = System.currentTimeMillis();
        long start = (Long) request.getAttribute("url_start");
        String ip = StringUtils.getRemoteAddr(request);
        String url = request.getRequestURL().toString();
        String method = request.getMethod();
        Map<String, String[]> params = request.getParameterMap();
        logger.info("[{}],[{}],[{}],[{}]", ip, url, method, JsonMapper.toJsonString(params), finished - start);
    }

    /**
     * 以JSON格式输出
     *
     * @param response
     */
    private void responseOutWithJson(HttpServletResponse response,
                                     Object responseObject) {
        if (!response.isCommitted()) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = null;
            try {
                out = response.getWriter();
                out.append(JsonMapper.toJsonString(responseObject));
            } catch (IOException e) {
                logger.error("验证登录信息发生异常。", e);
            } finally {
                if (out != null) {
                    out.flush();
                    out.close();
                }
            }
        }
    }
}
